﻿/*
 * 版 本 v1.0
 * Copyright (c) 2013-2018 广州市同慧信息科技有限公司
 * 创建人：ftquan
 * 日 期：2017.04.18
 * 描 述：新增表单
 */

var keyValue = request('keyValue');

var userdefault = {};
var bootstrap = function ($, learun) {
    "use strict";

    // 保存数据
    var acceptClick = function (type) {// 0保存并新增 1保存
        if (!$('.lr-layout-wrap').lrValidform()) {
            return false;
        }
        var formData = $('.lr-layout-wrap').lrGetFormData(keyValue);
        var productData = [];
        var productDataTmp = $('#productgird').jfGridGet('rowdatas');

        if (productDataTmp.length == 0) {
            learun.alert.error('表单信息不全,请检查！');
            return false;
        }

        for (var i = 0, l = productDataTmp.length; i < l; i++) {
            if (!!productDataTmp[i]['modelId']) {
                productDataTmp[i]['sort'] = i + 1;
                productData.push(productDataTmp[i]);
            }
        }
        if(productData.length == 0) {
            learun.alert.error('表单信息不全,请检查！');
            return;
        }
        var postData = formData;
        postData.detailList = productData;

        learun.layerConfirm('注：您确认要保存此操作吗？', function (res, index) {
            if (res) {

                $.lrSaveForm(config.base_server() + 'auditmodelwarnplans/saveOrUpdate?access_token=' + config.getToken().access_token + '&keyValue=' + keyValue, JSON.stringify(postData), function (res) {
                    if (res.resp_code == 200) {
                        // if (type == 0) {
                        //     window.location.href = config.webportal_server + 'pages/asset/clear/form.html?access_token=' + config.getToken().access_token
                        // }
                        // else {
                        //     learun.frameTab.close('clear_add');
                        // }
                    }
                });

                top.layer.close(index); //再执行关闭
            }
        });
    };

    var page = {
        init: function () {
            userdefault = learun.clientdata.get(['userinfo']);
            page.bind();
            page.initData();
        },
        bind: function () {
            // 优化滚动条
            $('.lr-layout-wrap').lrscroll();

            // 订单产品信息
            $('#productgird').jfGrid({
                headData: [
                    {
                        label: "模型信息", name: "a1", width: 80, align: "center", frozen: true,
                        children: [
                            {label: '模型id', name: 'modelId', width: 80, align: 'center'},
                            {
                                label: '模型名称', name: 'modelName', width: 360, align: 'left',
                                edit: {
                                    type: 'layer',
                                    init: function (data, $edit, rownum) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象

                                    },
                                    change: function (row, rownum, selectdatas) {// 行数据和行号,弹层选择行的数据，如果是自定义实现弹窗方式则该方法无效
                                        if (isRepeat(selectdatas)) {
                                            return;
                                        }

                                        $('#productgird').jfGridSet('updateRow', rownum);
                                        row.modelId = selectdatas[0].id;
                                        row.modelName = selectdatas[0].name;

                                        $('#productgird').jfGridSet('updateRow', rownum);

                                        if (selectdatas.length > 1) {
                                            for (var i = 1; i < selectdatas.length; i++) {
                                                var addrow = {};
                                                addrow.modelId = selectdatas[i].id;
                                                addrow.modelName = selectdatas[i].name;

                                                $('#productgird').jfGridSet('addRow', addrow);
                                            }
                                        }
                                    },
                                    op: { // 如果未设置op属性可以在init中自定义实现弹窗方式
                                        width: 1200,
                                        height: 600,
                                        colData: [
                                            {label: "模型id", name: "code", width: 120, align: "left"},
                                            {label: "模型名称", name: "name", width: 420, align: "left"},
//                                            {label: "类型, name: "categoryName", width: 120, align: "center"},
                                            {label: "主键", name: "id", width: 2, align: "center", hidden: true}
                                        ],
                                        url: config.base_server() + 'auditmodels/list?access_token=' + config.getToken().access_token,
                                        param: {status: 1},
                                        isMultiselect: true
                                    }
                                }
                            }

                        ]
                    },
                    {label: '结果文件url', name: 'resultUrl', width: 300, align: 'left'},
                    {
                       label: "操作", name: "btn2", width: 180, align: "center",
                       formatter: function (value, row, op, $cell) {
                           $cell.on('click', '.previewResult', function () {
                               if ($cell.html().trim() == '') {
                                   return false;
                               }
                               var code = row.modelId;
                               var keyValue = row.modelId;
                               var modelName = row.modelName;
                               if (learun.checkrow(keyValue)) {
                                   learun.layerForm({
                                       id: 'preview_result' + keyValue,
                                       title: '预览结果集',
                                       url: config.webportal_server + 'pages/finance/audit_rule/preview_result/result' + code + '.html?modelId=' + keyValue + '&access_token=' + config.getToken().access_token,
                                       width: 1000,
                                       height: 800,
                                       maxmin: true,
                                       btn: null
                                   });
                               }
                               return false;
                           });
                               return '<span class="label label-info previewResult" style="cursor: pointer;">预览</span>';
                       }
                    },
                ],
                isEdit: true,
                height: 300,
                isMultiselect: true
            });

            // 保存数据
            $('#savaAndAdd').on('click', function () {
                acceptClick(0);
            });
            $('#save').on('click', function () {
                acceptClick(1);
            });

            //初始化默认值
            var loginInfo = learun.clientdata.get(['userinfo']);
            $("#createUsername").val(loginInfo.user.realName);
            $("#createTime").val(new Date().format("yyyy-MM-dd"));
        },
        initData: function () {
            if (!!keyValue) {
                $.lrSetForm(config.base_server() + 'auditmodelwarnplans/findById?id=' + keyValue + '&access_token=' + config.getToken().access_token, function (data) {
                    $('.lr-layout-wrap').lrSetFormData(data);
                    //$("#departmentId").lrselectSet(data.departmentId);
                    $('#productgird').jfGridSet('refreshdata', data.detailList);
                });
            } else {
                $("#print").hide();
                $('#productgird').jfGridSet('addRow', {});
            }
        }
    };

    page.init();
}

//判断重复
function isRepeat(selectedRow) {
    var res = false;

    var productDataTmp = $('#productgird').jfGridGet('rowdatas');
    for (var i = 0; i < productDataTmp.length; i++) {
        for (var j = 0; j < selectedRow.length; j++) {
            if (productDataTmp[i].id == selectedRow[j].id) {
                top.learun.alert.warning('重复添加信息' + selectedRow[j].code + selectedRow[j].name);
                res = true;
                break;
            }
        }
    }

    return res;
}
